package com.nbcio.pm.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.nbcio.common.mybatis.core.page.PageQuery;
import com.nbcio.common.core.domain.R;
import com.nbcio.common.mybatis.core.page.TableDataInfo;
import com.nbcio.common.core.validate.AddGroup;
import com.nbcio.common.core.validate.EditGroup;
import com.nbcio.common.log.annotation.Log;
import com.nbcio.common.log.enums.BusinessType;
import com.nbcio.common.web.core.BaseController;
import com.nbcio.pm.domain.PmTeamRole;
import com.nbcio.pm.domain.bo.PmTeamRoleBo;
import com.nbcio.pm.domain.vo.PmTeamRoleVo;
import com.nbcio.pm.service.IPmTeamRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 团队角色
 *
 * @author nbacheng
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/pm/team/role")
public class PmTeamRoleController extends BaseController {

    private final IPmTeamRoleService pmTeamRoleService;

    /**
     * 查询团队角色列表
     */
    @SaCheckPermission("pm:team:view")
    @GetMapping("/list")
    public TableDataInfo<PmTeamRoleVo> list(PmTeamRoleBo bo, PageQuery pageQuery) {
        return pmTeamRoleService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询团队角色详细
     */
    @SaCheckPermission("pm:team:view")
    @GetMapping("/{roleId}")
    public R<PmTeamRoleVo> getInfo(@PathVariable Long roleId) {
        return R.ok(pmTeamRoleService.queryById(roleId));
    }

    /**
     * 新增团队角色
     */
    @SaCheckPermission("pm:team:manage")
    @Log(title = "团队角色", businessType = BusinessType.INSERT)
    @PostMapping
    public R<Void> add(@Validated(AddGroup.class) @RequestBody PmTeamRoleBo bo) {
        return toAjax(pmTeamRoleService.insertByBo(bo));
    }

    /**
     * 修改团队角色
     */
    @SaCheckPermission("pm:team:manage")
    @Log(title = "团队角色", businessType = BusinessType.UPDATE)
    @PutMapping
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody PmTeamRoleBo bo) {
        return toAjax(pmTeamRoleService.updateByBo(bo));
    }

    /**
     * 删除团队角色
     */
    @SaCheckPermission("pm:team:manage")
    @Log(title = "团队角色", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public R<Void> remove(@PathVariable Long[] roleIds) {
        return toAjax(pmTeamRoleService.deleteWithValidByIds(List.of(roleIds), true));
    }

    /**
     * 根据角色编码查询角色
     */
    @SaCheckPermission("pm:team:view")
    @GetMapping("/code/{roleCode}")
    public R<PmTeamRoleVo> getInfoByCode(@PathVariable String roleCode) {
        return R.ok(pmTeamRoleService.queryByRoleCode(roleCode));
    }

    /**
     * 查询用户拥有的角色列表
     */
    @SaCheckPermission("pm:team:view")
    @GetMapping("/user/{userId}")
    public R<List<PmTeamRoleVo>> getUserRoles(@PathVariable Long userId) {
        return R.ok(pmTeamRoleService.queryRolesByUserId(userId));
    }

    /**
     * 分配角色权限
     */
    @SaCheckPermission("pm:team:manage")
    @Log(title = "团队角色", businessType = BusinessType.UPDATE)
    @PostMapping("/assignPermissions")
    public R<Void> assignPermissions(@RequestBody Map<String, Object> params) {
        Long roleId = Long.valueOf(params.get("roleId").toString());
        @SuppressWarnings("unchecked")
        List<Object> permissionIdsObj = (List<Object>) params.get("permissionIds");
        
        // 安全转换权限ID列表为Long类型，支持长整型
        List<Long> permissionIds = permissionIdsObj.stream()
            .map(obj -> {
                if (obj instanceof Number) {
                    // 如果是数字类型，直接转换为Long
                    return ((Number) obj).longValue();
                } else {
                    // 如果是字符串，解析为Long
                    return Long.parseLong(obj.toString());
                }
            })
            .collect(Collectors.toList());
            
        return toAjax(pmTeamRoleService.assignRolePermissions(roleId, permissionIds));
    }

    /**
     * 查询角色权限列表
     */
    @SaCheckPermission("pm:team:view")
    @GetMapping("/permissions/{roleId}")
    public R<List<Long>> getRolePermissions(@PathVariable Long roleId) {
        return R.ok(pmTeamRoleService.queryRolePermissionIds(roleId));
    }
}
